﻿using Autofac;
using MeetAI.Repository;
using MeetAI.Repository.IRepository;
using MeetAI.Service;
using MeetAI.Service.IService;
using MeetAI.Utility;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Bootstrappers.Autofac;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;

namespace MeetAI.API
{
    public class ApplicationBootrapper : AutofacNancyBootstrapper
    {
        protected override void ConfigureApplicationContainer(ILifetimeScope container)
        {
            container.Update(builder =>
            {
                var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>()
                .Where(assembly => assembly.GetTypes().FirstOrDefault(type => type.GetInterfaces().Contains(typeof(IDependency))) != null);
                builder.RegisterAssemblyTypes(assemblies.ToArray())
                    .AsImplementedInterfaces()
                    .InstancePerDependency();
            });
        }

        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            StaticConfiguration.DisableErrorTraces = false;
            Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;
            pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
            {
                ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")
                    .WithHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS")
                    .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
            });
            pipelines.OnError += (ctx, ex) =>
            {
                Log.Error(ex);
                return null;
            };
        }
    }
}